package com.common.base.utils

import android.annotation.TargetApi
import android.app.Activity
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.core.app.ActivityCompat
import com.common.base.R
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropActivity
import java.io.File

object PhotoUtils {

    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     * @param imageUri
     * @author yaoxing
     * @date 2014-10-12
     */
    @TargetApi(19)
    fun getImageAbsolutePath(context: Context?, imageUri: Uri?): String? {
        if (context == null || imageUri == null)
            return null
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                val docId = DocumentsContract.getDocumentId(imageUri)
                val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val type = split[0]
                if ("primary".equals(type, ignoreCase = true)) {
                    return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                }
            } else if (isDownloadsDocument(imageUri)) {
                val id = DocumentsContract.getDocumentId(imageUri)
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id))
                return getDataColumn(context, contentUri, null, null)
            } else if (isMediaDocument(imageUri)) {
                val docId = DocumentsContract.getDocumentId(imageUri)
                val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val type = split[0]
                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }
                val selection = MediaStore.Images.Media._ID + "=?"
                val selectionArgs = arrayOf(split[1])
                return getDataColumn(context, contentUri, selection, selectionArgs)
            }
        } // MediaStore (and general)
        else if ("content".equals(imageUri.scheme!!, ignoreCase = true)) {
            // Return the remote address
            return if (isGooglePhotosUri(imageUri)) imageUri.lastPathSegment else getDataColumn(context, imageUri, null, null)
        } else if ("file".equals(imageUri.scheme!!, ignoreCase = true)) {
            return imageUri.path
        }// File
        return null
    }

    fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
        var cursor: Cursor? = null
        val column = MediaStore.Images.Media.DATA
        val projection = arrayOf(column)
        try {
            cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null)
            if (cursor != null && cursor.moveToFirst()) {
                val index = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(index)
            }
        } finally {
            cursor?.close()
        }
        return null
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.authority
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    fun isDownloadsDocument(uri: Uri): Boolean {
        return "com.android.providers.downloads.documents" == uri.authority
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    fun isGooglePhotosUri(uri: Uri): Boolean {
        return "com.google.android.apps.photos.content" == uri.authority
    }
    /**
     * *********************************以上*****************************************
     */


    /**
     * 打开图库
     */
    fun goPhotoAlbum(activity: Activity, reqCode: Int) {
        var intent = Intent()
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            intent.action = Intent.ACTION_GET_CONTENT
            intent.type = "image/*"
        } else {
            intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        }
        activity.startActivityForResult(intent, reqCode)
    }

    /**
     * 打开相机
     */
    fun goPhoneCamera(activity: Activity, fileUri: Uri, reqCode: Int) {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
        activity.startActivityForResult(intent, reqCode)
    }

    /**
     * 判断手机是否存在SD卡
     * @return
     */
    fun isExistSDCard(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }


    /**
     * 获得SD卡剩余空间
     * @return
     */
    fun getSDFreeSize(): Long {
        //取得SD卡文件路径
        val path = Environment.getExternalStorageDirectory()
        val sf = StatFs(path.path)
        //获取单个数据块的大小(Byte)
        val blockSize = sf.blockSize.toLong()
        //空闲的数据块的数量
        val freeBlocks = sf.availableBlocks.toLong()
        //返回SD卡空闲大小
        //return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
        return freeBlocks * blockSize / 1024 / 1024 //单位MB
    }

    /**
     * 启动裁剪
     * @param activity 上下文
     * @param sourceFilePath 需要裁剪图片的绝对路径
     * @param requestCode 比如：UCrop.REQUEST_CROP
     * @param aspectRatioX 裁剪图片宽高比
     * @param aspectRatioY 裁剪图片宽高比
     * @return
     */
    fun startUCrop(activity: Activity, sourceFilePath: String,
                   requestCode: Int): String {
        val sourceUri = Uri.fromFile(File(sourceFilePath))
        val outDir = AppUtils.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val outFile = File(outDir, System.currentTimeMillis().toString() + ".jpg")
        //裁剪后图片的绝对路径
        val cameraScalePath = outFile.absolutePath
        val destinationUri = Uri.fromFile(outFile)
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        val uCrop = UCrop.of(sourceUri, destinationUri, ArrayList())
        //初始化UCrop配置
        val options = UCrop.Options()
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL)
        //是否隐藏底部容器，默认显示
        options.setHideBottomControls(true)
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(activity, R.color.colorPrimary))
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.colorPrimary))
        options.setShowCropGrid(false)  //设置是否显示裁剪网格
        //是否能调整裁剪框
        //        options.setFreeStyleCropEnabled(true)
        //UCrop配置
        uCrop.withOptions(options)
        //设置裁剪图片的宽高比，比如16：9
        uCrop.withAspectRatio(1f, 1f)
        uCrop.withMaxResultSize(1000,1000)
        //uCrop.useSourceImageAspectRatio();
        //跳转裁剪页面
        uCrop.start(activity, requestCode)
        return cameraScalePath
    }

    fun startCropForCover(activity: Activity,
                   sourceFilePath: String,
                   requestCode: Int,
                   ratioX:Float = 16f,
                   ratioY:Float = 9f,
                   maxWidth:Int = 1280,
                   maxHeight:Int = 720): String {
        val sourceUri = Uri.fromFile(File(sourceFilePath))
        val outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        if (!outDir.exists()) {
            outDir.mkdirs()
        }
        val outFile = File(outDir, System.currentTimeMillis().toString() + ".jpg")
        //裁剪后图片的绝对路径
        val cameraScalePath = outFile.absolutePath
        val destinationUri = Uri.fromFile(outFile)
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        val uCrop = UCrop.of(sourceUri, destinationUri,ArrayList())
        //初始化UCrop配置
        val options = UCrop.Options()
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL)
        //是否隐藏底部容器，默认显示
        options.setHideBottomControls(true)
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(activity, R.color.colorPrimary))
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.colorPrimary))
        options.setShowCropGrid(false)  //设置是否显示裁剪网格
//        options.setToolbarCancelDrawable(R.drawable.ic_logo_launcher)
//        options.setToolbarTitle("测试")

        //是否能调整裁剪框
        //        options.setFreeStyleCropEnabled(true)
        //UCrop配置
        uCrop.withOptions(options)
        //设置裁剪图片的宽高比，比如16：9
        uCrop.withAspectRatio(ratioX, ratioY)

        uCrop.withMaxResultSize(maxWidth,maxHeight)
        //uCrop.useSourceImageAspectRatio();
        //跳转裁剪页面
        uCrop.start(activity, requestCode)
        return cameraScalePath
    }

//    //设置Toolbar标题
//    void setToolbarTitle(@Nullable String text)
//    //设置裁剪的图片格式
//    void setCompressionFormat(@NonNull Bitmap.CompressFormat format)
//    //设置裁剪的图片质量，取值0-100
//    void setCompressionQuality(@IntRange(from = 0) int compressQuality)
//    //设置最多缩放的比例尺
//    void setMaxScaleMultiplier(@FloatRange(from = 1.0, fromInclusive = false) float maxScaleMultiplier)
//    //动画时间
//    void setImageToCropBoundsAnimDuration(@IntRange(from = 100) int durationMillis)
//    //设置图片压缩最大值
//    void setMaxBitmapSize(@IntRange(from = 100) int maxBitmapSize)
//    //是否显示椭圆裁剪框阴影
//    void setOvalDimmedLayer(boolean isOval)
//    //设置椭圆裁剪框阴影颜色
//    void setDimmedLayerColor(@ColorInt int color)
//    //是否显示裁剪框
//    void setShowCropFrame(boolean show)
//    //设置裁剪框边的宽度
//    void setCropFrameStrokeWidth(@IntRange(from = 0) int width)
//    //是否显示裁剪框网格
//    void setShowCropGrid(boolean show)
//    //设置裁剪框网格颜色
//    void setCropGridColor(@ColorInt int color)
//    //设置裁剪框网格宽
//    void setCropGridStrokeWidth(@IntRange(from = 0) int width)
}